package pers.cocoadel.rule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class MyRule extends AbstractLoadBalancerRule
{
    private final static int[] indexs = new int[]{0, 0, 1};


    private final AtomicInteger atomicInteger = new AtomicInteger(0);

    private int getAndIncrement()
    {
        int currentIndex;
        int index;
        do
        {
            currentIndex = atomicInteger.get();
            index = currentIndex == 0x7ffffff ? 0 : currentIndex + 1;
        }
        while (!atomicInteger.compareAndSet(currentIndex, index));
        return index;
    }

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig)
    {

    }

    @Override
    public Server choose(Object o)
    {
        ILoadBalancer lb = getLoadBalancer();
        Server server;
        while (true)
        {
            if (Thread.interrupted())
            {
                return null;
            }
            List<Server> allServers = lb.getAllServers();
            List<Server> upServers = lb.getReachableServers();
            if (allServers.size() == 0)
            {
                return null;
            }

            int index = 0;
            if (allServers.size() > 1)
            {
                index = getAndIncrement();
                index = indexs[index % 3];
            }

            server = upServers.get(index);
            if (server == null)
            {
                Thread.yield();
                continue;
            }

            if (server.isAlive())
            {
                System.out.printf("第%s次请求，index：%s，服务名称：%s\n", atomicInteger.get(), index, server.getHostPort());
                return (server);
            }
            Thread.yield();
        }

    }
}
